<template>
  <div>
    <!-- 批量收款   -->
    <div class="pay-dialog">
      <el-dialog :show-close="false" v-model="visiblePlay" title="批量收款" width="800">
        <div class="customers">
          <div>
            关联客户 ：
            <el-select-v2
              v-model="customerId"
              filterable
              :options="options"
              placeholder="请选择"
              style="width: 300px"
              value-key="userId"
              :props="{ value: 'userId', label: 'userName' }"
              @change="selectChange"
            />
          </div>
          <div>
            <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
            <el-button type="primary" plain :icon="RefreshRight" @click="handleRefresh">重置</el-button>
          </div>
        </div>
        <el-table
          ref="tableRef"
          :data="tableData"
          stripe
          style="width: 100%"
          border
          height="400"
          :header-cell-style="{ background: '#F2F6FC', color: '#4E5969', 'font-weight': 400, 'font-size': '14px' }"
          row-key="reformId"
          @selection-change="selectionPlayChange"
        >
          <el-table-column type="selection" reserve-selection width="55" fixed="left" />
          <el-table-column label="售后分类" show-overflow-tooltip prop="reformTypeName" />
          <el-table-column label="关联客户" show-overflow-tooltip prop="customerName" />
          <el-table-column label="问题描述" show-overflow-tooltip prop="ownerVisibleContent" />
          <el-table-column label="已收款/应收款" show-overflow-tooltip prop="reformDesc">
            <template #default="{ row }">
              {{ row.amountReceived + "/" + row.customerTotalPaymentDue }}
            </template>
          </el-table-column>
          <el-table-column label="发起人" show-overflow-tooltip prop="submitUserName" />
          <el-table-column label="发起时间" show-overflow-tooltip prop="submitTime" />
        </el-table>
        <template #footer>
          <div>已选待付款合计：¥ {{ sumMoney }}</div>
          <span class="dialog-footer">
            <el-button @click="visiblePlay = false" color="#F2F3F5">取消</el-button>
            <el-button type="primary" @click="handlePlaySubmit">确认</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
    <!--  批量支付  -->
    <div class="play-contain">
      <el-dialog v-model="payVisible" width="800" center :show-close="false" :close-on-click-modal="false">
        <template #title>
          <title-view title="收款" />
        </template>
        <el-row :gutter="24" class="mb20">
          <el-col :span="8">
            <div>客户: {{ customerName }}</div>
          </el-col>
          <el-col :span="8">
            <div>需收款金额: {{ (sumMoney > 0 && sumMoney) || sumMoneyOne }}</div>
          </el-col>
          <el-col :span="8">
            <div>本次收款金额合计: {{ sumMoneys }}</div>
          </el-col>
        </el-row>

        <el-form
          ref="rulePlayFormRef"
          label-width="100px"
          style="width: 100%"
          :model="rulePlayForm"
          :rules="rulesPlay"
          class="demo-ruleForm"
        >
          <el-form-item
            label="支付方式"
            prop="checkbox"
            required
            :rules="{ required: true, message: '请选择支付方式', trigger: 'change' }"
          >
            <el-checkbox-group v-model="rulePlayForm.checkbox">
              <el-checkbox :value="1">账户支付</el-checkbox>
              <el-checkbox :value="2">现金支付</el-checkbox>
              <el-checkbox :value="3">预收款支付</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <div v-if="rulePlayForm.checkbox?.includes(1)">
            <div class="title">账户支付</div>
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item
                  label="收款金额"
                  prop="payObjOne.money"
                  :rules="{ required: true, message: '请输入收款金额', trigger: 'blur' }"
                >
                  <el-input type="number" v-model="rulePlayForm.payObjOne.money" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="收款账户"
                  prop="payObjOne.accountId"
                  required
                  :rules="{ required: true, message: '请选择收款账户', trigger: 'change' }"
                >
                  <el-select v-model="rulePlayForm.payObjOne.accountId" placeholder="请选择">
                    <el-option
                      v-for="item in accountList"
                      :value="item.accountId"
                      :key="item.accountId"
                      :label="item.dictName + '-' + item.account"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="收款日期"
                  prop="payObjOne.receiptDateStr"
                  required
                  :rules="{ required: true, message: '请选择收款日期', trigger: 'change' }"
                >
                  <el-date-picker
                    v-model="rulePlayForm.payObjOne.receiptDateStr"
                    type="date"
                    style="flex: 1"
                    value-format="YYYY-MM-DD"
                    placeholder="请选择"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item
              label="支付凭证"
              prop="payObjOne.fileVos"
              required
              :rules="{ required: true, message: '请上传支付凭证', trigger: 'change' }"
            >
              <image-video-upload
                :fileList="rulePlayForm.payObjOne?.fileVos"
                tip="只能上传jpg/png/jpeg，且不超过10M,最大支持上传6张"
                accept=".jpg,.png,.jpeg"
                multiple
                :max-size="10"
                :max-length="6"
                @upload-success="e => uploadImage(e, 1)"
                @upload-remove="e => uploadImageRemove(e, 1)"
              />
            </el-form-item>
          </div>
          <div v-if="rulePlayForm.checkbox?.includes(2)">
            <el-divider />
            <div class="title">现金支付</div>
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item
                  label="收款金额"
                  prop="payObjTwo.money"
                  required
                  :rules="{ required: true, message: '请输入收款金额', trigger: 'blur' }"
                >
                  <el-input type="number" v-model="rulePlayForm.payObjTwo.money" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="收款日期"
                  prop="payObjTwo.receiptDateStr"
                  required
                  :rules="{ required: true, message: '请选择收款日期', trigger: 'change' }"
                >
                  <el-date-picker
                    v-model="rulePlayForm.payObjTwo.receiptDateStr"
                    type="date"
                    style="flex: 1"
                    value-format="YYYY-MM-DD"
                    placeholder="请选择"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item
              label="支付凭证"
              prop="payObjTwo.fileVos"
              required
              :rules="{ required: true, message: '请上传支付凭证', trigger: 'change' }"
            >
              <image-video-upload
                :fileList="rulePlayForm.payObjTwo?.fileVos"
                tip="只能上传jpg/png/jpeg，且不超过10M,最大支持上传6张"
                accept=".jpg,.png,.jpeg"
                multiple
                :max-size="10"
                :max-length="6"
                @upload-success="e => uploadImage(e, 2)"
                @upload-remove="e => uploadImageRemove(e, 2)"
              />
            </el-form-item>
          </div>
          <div v-if="rulePlayForm.checkbox?.includes(3)">
            <el-divider />
            <div class="title">预收款支付</div>
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item
                  label="收款金额"
                  prop="payObjThree.money"
                  required
                  :rules="{ required: true, message: '预收款支付没有使用的单据', trigger: 'blur' }"
                >
                  <el-input disabled type="number" v-model="rulePlayForm.payObjThree.money" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="收款日期"
                  prop="payObjThree.receiptDateStr"
                  required
                  :rules="{ required: true, message: '请选择收款日期', trigger: 'change' }"
                >
                  <el-date-picker
                    v-model="rulePlayForm.payObjThree.receiptDateStr"
                    type="date"
                    style="flex: 1"
                    value-format="YYYY-MM-DD"
                    placeholder="请选择"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="预收款核销">
              <el-table
                :data="rulePlayForm.payObjThree?.advancesReceivedList"
                style="width: 100%"
                :header-cell-style="{ background: '#F2F6FC', color: '#4E5969', 'font-weight': 400, 'font-size': '14px' }"
                class="advances-table"
              >
                <el-table-column prop="slipCode" label="单号" />
                <el-table-column prop="notUseMoney" label="未使用金额" />
                <el-table-column prop="money" label="本单使用">
                  <template #default="{ row, $index }">
                    <el-form-item
                      label=""
                      :prop="`payObjThree.advancesReceivedList[${$index}].money`"
                      :rules="[
                        {
                          validator: (rule, value, callback) => requiredRule(rule, value, callback, $index),
                          trigger: 'blur'
                        }
                      ]"
                    >
                      <el-input type="number" v-model="row.money" placeholder="请输入" :min="0" />
                    </el-form-item>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </div>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="payVisible = false">取消</el-button>
            <el-button type="primary" @click="payConfirm"> 确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { RefreshRight, Search } from "@element-plus/icons-vue";
import { computed, ref, watch } from "vue";
import {
  available,
  getCustomerByName,
  getMyAccountList,
  getSlipDetail,
  payment,
  paymentOrder
} from "@/apis/rectificationManager";
import { ElMessage } from "element-plus";
import { cloneDeep } from "lodash";

const accountList = ref([]);
const options = ref([]);
const tableData = ref([]);
const selectData = ref([]);
const customerId = ref("");
const customerName = ref("");
const tableRef = ref(null);
const rulesPlay = ref({});
const slipId = ref([]);
const reformId = ref([]);
const isBatch = ref(false); // 是否是批量支付
const visiblePlay = ref(false);
const payVisible = ref(false);
const sumMoneyOne = ref(0);
// 收款
const rulePlayFormRef = ref();
const rulePlayForm = ref({});
const initRulePlayForm = () => {
  rulePlayForm.value = {
    checkbox: [],
    payObjOne: {
      payType: 1,
      receiptDateStr: "",
      money: "",
      accountId: "",
      fileVos: []
    },
    payObjTwo: {
      payType: 2,
      receiptDateStr: "",
      money: "",
      fileVos: []
    },
    payObjThree: {
      payType: 3,
      receiptDateStr: "",
      money: "",
      advancesReceivedList: []
    }
  };
};
const requiredRule = (rule, value, callback, index) => {
  if (value) {
    if (Number(value) > Number(rulePlayForm.value.payObjThree.advancesReceivedList[index].notUseMoney)) {
      callback(new Error("不能大于未使用金额"));
    } else {
      callback();
    }
  } else {
    callback();
  }
};
const sumMoney = computed(() => {
  let sumMoney = 0;
  let sumMoney1 = 0;
  selectData.value.length > 0 &&
    selectData.value.forEach(item => {
      sumMoney += Number(item.amountReceived) * 100;
      sumMoney1 += Number(item.customerTotalPaymentDue) * 100;
    });
  return ((sumMoney1 - sumMoney) / 100).toFixed(2);
});
const sumMoneys = computed(() => {
  let sumMoney1 = rulePlayForm.value?.payObjOne?.money || 0;
  let sumMoney2 = rulePlayForm.value?.payObjTwo?.money || 0;
  let sumMoney3 = rulePlayForm.value?.payObjThree?.money || 0;
  console.log(sumMoney1, sumMoney2, sumMoney3);
  return ((Number(sumMoney1) * 100 + Number(sumMoney2) * 100 + Number(sumMoney3) * 100) / 100).toFixed(2);
});
const slipIds = computed(() => {
  let ids = [];
  selectData.value.length > 0 &&
    selectData.value.forEach(item => {
      ids.push(item.slipId);
    });
  return ids;
});
const reformIds = computed(() => {
  let ids = [];
  selectData.value.length > 0 &&
    selectData.value.forEach(item => {
      ids.push(item.reformId);
    });
  return ids;
});
const selectChange = val => {
  customerName.value = options.value.find(item => item.userId === val).userName;
};
watch(
  () => rulePlayForm.value.payObjThree?.advancesReceivedList,
  newVal => {
    let sum = 0;
    newVal &&
      newVal.length > 0 &&
      newVal.forEach(item => {
        if (Number(item.money) > 0) {
          sum += Number(item.money) * 100;
        }
      });
    rulePlayForm.value.payObjThree.money = sum / 100;
  },
  { deep: true }
);
// 上傳
const uploadImage = (list, i) => {
  switch (i) {
    case 1:
      rulePlayForm.value.payObjOne.fileVos.push(list);
      break;
    case 2:
      rulePlayForm.value.payObjTwo.fileVos.push(list);
      break;
  }
};
//
const uploadImageRemove = (index, i) => {
  switch (i) {
    case 1:
      rulePlayForm.value.payObjOne.fileVos.splice(index, 1);
      break;
    case 2:
      rulePlayForm.value.payObjTwo.fileVos.splice(index, 1);
      break;
  }
};
const getSlipDetailId = async () => {
  let id = isBatch.value ? selectData.value[0].slipId : slipId.value;
  const { data } = await getSlipDetail(id);
  await getAvailable(data.partnerId);
};
const getAvailable = async partnerId => {
  const { data } = await available(partnerId);
  rulePlayForm.value.payObjThree.advancesReceivedList = data || [];
};
watch(
  () => rulePlayForm?.value?.checkbox,
  newVal => {
    if (newVal?.includes(1) === false) {
      console.log(1);
      rulePlayForm.value.payObjOne = {
        payType: 1,
        receiptDateStr: "",
        money: "",
        accountId: "",
        fileVos: []
      };
    }
    if (newVal?.includes(2) === false) {
      console.log(2);
      rulePlayForm.value.payObjTwo = {
        payType: 2,
        receiptDateStr: "",
        money: "",
        fileVos: []
      };
    }
    if (newVal?.includes(3) === false) {
      let advancesReceivedList = rulePlayForm.value?.payObjThree?.advancesReceivedList;
      if (advancesReceivedList && advancesReceivedList.length > 0) {
        advancesReceivedList = advancesReceivedList.map(item => {
          return {
            ...item,
            money: ""
          };
        });
      }
      rulePlayForm.value.payObjThree = {
        payType: 3,
        receiptDateStr: "",
        money: "",
        advancesReceivedList
      };
    }
  },
  { deep: true }
);
const getAccount = async () => {
  const { data } = await getMyAccountList({ status: 1 });
  accountList.value = data.list || [];
};
getAccount();
// 确认收款
const payConfirm = async () => {
  await rulePlayFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      let params = {
        slipIds: isBatch.value ? slipIds.value : slipId.value,
        reformIds: isBatch.value ? reformIds.value : reformId.value,
        customerId: customerId.value,
        slipPayList: []
      };
      let payObjThree = cloneDeep(rulePlayForm.value.payObjThree);
      let advancesReceivedList = [];
      if (payObjThree?.advancesReceivedList?.length > 0) {
        payObjThree?.advancesReceivedList.forEach(item => {
          if (item.money && Number(item.money) > 0) {
            console.log(item);
            advancesReceivedList.push(item);
          }
        });
      }
      payObjThree.advancesReceivedList = advancesReceivedList;
      const payObjects = [rulePlayForm.value.payObjOne, rulePlayForm.value.payObjTwo, payObjThree];
      rulePlayForm.value.checkbox.forEach(checkedIndex => {
        if (checkedIndex >= 1 && checkedIndex <= 3) {
          params.slipPayList.push(payObjects[checkedIndex - 1]);
        }
      });
      await payment(params);
      rulePlayFormRef.value.resetFields();
      payVisible.value = false;
      ElMessage.success("收款成功");
    } else {
      console.log(fields);
    }
  });
};
// 选择批量收款数据
const selectionPlayChange = val => {
  selectData.value = val;
};
// 确认批量收款
const handlePlaySubmit = async () => {
  if (selectData.value.length <= 0 && sumMoney.value <= 0) {
    ElMessage.error("请勾选单据或勾选的部分单据暂无需收款金额");
    return;
  }
  visiblePlay.value = false;
  payVisible.value = true;
  await getSlipDetailId();
};

// 打开批量收款
const openVisible = async id => {
  isBatch.value = true;
  initRulePlayForm();
  tableRef.value?.clearSelection();
  selectData.value = [];
  customerId.value = id ? id : "";
  customerName.value = "";
  tableData.value = [];
  visiblePlay.value = true;
  const { data } = await getCustomerByName();
  options.value = data || [];
  if (id) {
    customerName.value = options.value.find(item => item.userId === id).userName;
    await handleSearch();
  }
};
// 查询列表
const handleSearch = async () => {
  tableRef.value?.clearSelection();
  const { data } = await paymentOrder({ customerId: customerId.value });
  tableData.value = data || [];
};
// 重置
const handleRefresh = () => {
  tableRef.value?.clearSelection();
  customerId.value = "";
  customerName.value = "";
  tableData.value = [];
};
// 单个收款打开
const open = async row => {
  initRulePlayForm();
  isBatch.value = false;
  customerName.value = row.customerName;
  customerId.value = row.customerId;
  reformId.value = row.reformId;
  slipId.value = (row.slipId && row.slipId) || [];
  sumMoneyOne.value = row.sumMoneys;
  payVisible.value = true;
  await getSlipDetailId();
};
defineExpose({ openVisible, open });
</script>
<style scoped lang="scss">
.customers {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.title {
  font-size: 14px;
  font-weight: 600;
  margin-bottom: 10px;
}

.pay-dialog {
  :deep(.el-dialog__footer) {
    display: flex !important;
    justify-content: space-between;
    align-items: center;
  }
}

.dialog-footer {
  text-align: center;

  :deep(.el-button) {
    width: 120px !important;
    height: 36px !important;
  }
}

.advances-table {
  :deep(.el-form-item) {
    margin-bottom: 18px !important;
  }
}
</style>
